/*
 * Copyright (c) 2015 DHC Corporation.
 */
package cn.com.dhc.danlu.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Miscellaneous agent utility methods.
 */
public class AgentUtils {
    /**
     * Package Info
     */
    private static PackageInfo packageInfo;

    /**
     * Get Package Info
     */
    public static PackageInfo getPackageInfo (Context context) {
        if (packageInfo == null) {
            try {
                packageInfo = context.getPackageManager ().getPackageInfo (context.getPackageName (), 0);
            } catch (NameNotFoundException e) {
                packageInfo = new PackageInfo ();
            }
        }
        return packageInfo;
    }

    /**
     * Get Version Name
     */
    public static String getVersionName () {
        if (packageInfo != null) {
            return packageInfo.versionName;
        }
        return "-";
    }

    /**
     * 检测网络是否可用
     *
     * @param context
     *         Context
     * @return 网络是否可用
     */
    public static boolean isNetworkAvailable (Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE);
            // 获取网络连接信息，如果无网络可用，就不需要进行连网操作
            NetworkInfo networkInfo = cm.getActiveNetworkInfo ();
            // 检测网络是否可用
            return null != networkInfo && networkInfo.isAvailable ();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查网络是否连接上
     *
     * @param context
     *         Context
     * @return 网络是否连接上
     */
    public static boolean isNetworkConnected (Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE);
        // 获取网络连接信息，如果无网络可用，就不需要进行连网操作
        NetworkInfo info = cm.getActiveNetworkInfo ();
        if (info == null) {
            return false;
        }
        // 检查网络是否连接上
        return info.isConnected ();
    }
}